package com.ang.aop.aspect;

import cn.hutool.core.util.StrUtil;
import com.ang.aop.annotation.SysAuthDemo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
public class SysAuthDemoAspect {

    @Pointcut("@annotation(com.ang.aop.annotation.SysAuthDemo)")
    public void annotationPointCut(){

    }

    @Around(value = "annotationPointCut()")
    public Object Around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 获取切入点所在的方法
        Method method = methodSignature.getMethod();
        // 获取注解对象
        SysAuthDemo annotation = method.getAnnotation(SysAuthDemo.class);

        StringBuffer result = new StringBuffer();

        if(StrUtil.isNotEmpty(annotation.hasAuth())){
            result = result.append(annotation.hasAuth());
            if(isHasAuth(annotation.hasAuth())){
                return joinPoint.proceed();
            }
        }
        else if(StrUtil.isNotEmpty(annotation.hasRole())){
            result = result.append(annotation.hasRole());
            if(isHasRole(annotation.hasRole())){
                return joinPoint.proceed();
            }
        }
        else if(annotation.hasAnyAuth().length > 0){
            for(String auth : annotation.hasAnyAuth()){
                result = result.append(auth);
            }
            if(isHasAnyAuth(annotation.hasAnyAuth())){
                return joinPoint.proceed();
            }
        }
        System.out.println("-------------------------");
        System.out.println(String.format("没有%s权限",result.toString()));
        System.out.println("-------------------------");
        return null;
    }

    //判断是否包含某个权限
    public boolean isHasAuth(String auth){
        //模拟当前用户拥有的权限
        List<String> authList = Arrays.asList("add","list");
        if(authList.contains(auth)){
            return true;
        }
        return false;
    }

    //判断是否包含否个角色
    public boolean isHasRole(String role){
        //模拟当前用户拥有的角色
        List<String> roleList = Arrays.asList("user");
        if(roleList.contains(role)){
            return true;
        }
        return false;
    }

    //是否包含其中一个权限
    public boolean isHasAnyAuth(String[] authArr){
        //模拟当前用户拥有的权限
        List<String> authList = Arrays.asList("add","list");
        String hasAuth = authList.stream()
                .filter(auth->Arrays.asList(authArr).contains(auth))
                .findAny()
                .orElse("");

        if(StrUtil.isNotEmpty(hasAuth)){
            return true;
        }

        return false;
    }
}
